~ function(){
    var LS = {};
    LS.UI = function(){
        var POPUP_HEIGHT_PER_FRAME = 110;
        var POPUP_HEIGHT_TOTAL = 2200;
        
        var tbInReplyTo = $('#in_reply_to');
        var tbStatus = $('#status');
        var board = $('#topNotice');
        var icon = $('#notice-icon');
        var textArea = $('#notice-text');
        var counterWrapper = $('#postCounter');
        var countArea = $('#text-counter-count');
        var countStatus = $('#text-counter-status');
        var popupClickMe = $('.clickmepop');
        var timeline = $("#timeline");
        var latestStatus = $('#lastate');
        var updateCounter = $('#updateCounter');
        var msgBox = $('#tkyou');
	
	var lastReadItem;
        
        var title = document.title;
        var unreadCount = 0;
        var username = $('#screen-name').val();
        var rtFormat = $('#rt-format').val();
        
        var popupTarget;
        
        var autoUpdate = true;
        
        var _ICON_STATE = {
            SUCCESS: 1,
            ERROR: 2,
            INFO: 3,
            WARNING: 4,
            QUESTION: 5
        }
        
        var _updateStatus = function(statusText, inReplyTo, cursorPos){
            tbStatus.val(statusText);
            tbInReplyTo.val(inReplyTo);
            if (cursorPos !== null) {
                tbStatus.attr({
                    selectionStart: cursorPos,
                    selectionEnd: cursorPos
                });
            }
            tbStatus.focus();
        }
        
        var _updateNotice = function(text, state, showTime, duration){
            state = state || LS.UI.ICON_STATE.SUCCESS;
            showTime = showTime || 3000;
            duration = duration || 300;
            textArea.html(text);
            icon.attr('class', 't-notice-ico-' + state);
            board.slideDown(duration, function(){
                setTimeout(function(){
                    board.slideUp(duration, function(){
                        board.hide();
                    });
                }, showTime);
            });
        }
        
        var _updateTitle = function(){
            document.title = unreadCount ? "(" + unreadCount + ") " + title : title;
        }
        
        var _updateTextCounter = function(){
            var len = tbStatus.val().length;
            if (len <= 140) {
                countArea.html(140 - len);
                countStatus.html('还可以输入');
                counterWrapper.css('color', '#B3B3B3');
            }
            else {
                countArea.html(len - 140);
                countStatus.html('已超出');
                counterWrapper.css('color', '#FF3300');
            }
        }
        
        var _showPopup = function(e){
            popupTarget = $(e.target);
            popupClickMe.css({
                left: (popupTarget.offset().left - popupClickMe.width()) + 'px',
                top: (popupTarget.offset().top - popupClickMe.height() + 20) + 'px',
                backgroundPosition: '0 0'
            }).show().find('a').hide();
            var y = 0;
            var t = setInterval(function(){
                if (y <= -(POPUP_HEIGHT_TOTAL - POPUP_HEIGHT_PER_FRAME)) {
                    clearInterval(t);
                    popupClickMe.find('a').show();
                }
                popupClickMe.css('background-position', '0 ' + y + 'px');
                y -= POPUP_HEIGHT_PER_FRAME;
            }, 30);
        }
        
        var _updateLatest = function(text){
            latestStatus.attr('title', text);
            latestStatus.find('span').html(text);
        }
        
        var _getNewTimeLine = function(){
            if (!autoUpdate) 
                return;
	    lastReadItem = timeline.find('li:not(.new):first');
            $.ajax({
                url: "ajax/home_time_line",
                type: 'POST',
                data: {
                    since_id: lastReadItem.attr('id')
                },
                success: function(html){
                    if (!html) 
                        return;
                    var stack = [];
		    $(html).find('li').each(function(index){
                        stack.push($(this));
                    });
                    while (stack.length > 0) {
                        var item = stack.pop().prependTo(timeline).hide();
                        if ($.trim(item.find('.username').html()) !== username) {
                            item.addClass('unread');
                            unreadCount++;
                        }
                    }
                    if (unreadCount > 0) {
                        _updateTitle();
                        msgBox.slideDown().find('span').html(unreadCount);
                    }
                    /*
                     var scrollTop = $(window).scrollTop();
                     var scrollOffset = 0;
                     timeline.find('li.new').each(function() {
                     var itemToDeleted = $(this);
                     scrollOffset -= (itemToDeleted.height() + 30);
                     itemToDeleted.remove();
                     });
                     $(html).find('li').each(function() {
                     var item = $(this);
                     if (item.find('.username').html() !== username) {
                     item.addClass('new-item');
                     unreadCount++;
                     }
                     item.prependTo(timeline);
                     scrollOffset += (item.height() + 30);
                     });
                     $(window).scrollTop(scrollTop + scrollOffset);
                     /*
                     var stack = [];
                     $(html).find('li').each(function(){
                     stack.push(this);
                     });
                     unreadCount += stack.length;
                     var animInsert = function(){
                     if (stack.length === 0)
                     return;
                     var item = $(stack.pop());
                     if (item.find('.username').html() !== username) {
                     item.addClass('new-item');
                     } else {
                     unreadCount--;
                     }
                     item.prependTo(timeline);
                     timeline.css({
                     'margin-top': -80 + 'px'
                     }).animate({
                     marginTop: 0
                     }, 200, function(){
                     setTimeout(animInsert, 500);
                     });
                     }
                     animInsert();
                     */
                }
            });
        }
        
        var _reset = function(){
            popupClickMe.hide();
	    /*
            $('#timeline li').removeClass('new-item');
            unreadCount = 0;
            _updateTitle();
		      */
        }
        
        var _attachEvents = function(){
        
            $('.reply').live('click', function(e){
                var li = $(this).closest("li");
                _updateStatus('@' + li.find('.username').html() + ' ', li.attr('id'));
                e.preventDefault();
            });
            
            $('.clickme').live('click', function(e){
                _showPopup(e);
                e.preventDefault();
            });
            
            tbStatus.keypress(function(e){
                setTimeout(function(){
                    _updateTextCounter();
                }, 0);
            });
            
            $('#autoSwitch').click(function(){
                var handle = $(this).find('.handle');
                autoUpdate = !autoUpdate;
                handle.animate({
                    left: (autoUpdate ? 0 : 17) + 'px'
                }, 100);
            });
            
            popupClickMe.find('a').click(function(e){
                e.preventDefault();
            });
            
            $('#quote').click(function(e){
                var PATTERN = rtFormat;
                var li = popupTarget.closest("li");
                var user = $.trim(li.find('.username').text());
                var content = $.trim(li.find('.content').text());
                var text = PATTERN.replace('{user}', user).replace('{content}', content);
                var pos = text.indexOf('{cursor}');
                text = text.replace('{cursor}', '');
                _updateStatus(text, '', pos);
            });
            
            $('#retweet').click(function(e){
                var li = popupTarget.closest("li");
                $.ajax({
                    type: 'POST',
                    url: 'ajax/retweet',
                    data: {
                        status_id: li.attr('id')
                    },
                    success: function(){
                        _updateNotice('转推成功！');
                    },
                    error: function(){
                        _updateNotice('转推失败，你可以已经转发过此推。', LS.UI.ICON_STATE.ERROR);
                    }
                })
            });
            
            $('.fav').live('click', function(e){
                var self = $(this);
                $.ajax({
                    url: "ajax/add_fav",
                    type: 'POST',
                    data: {
                        id: self.closest('li').attr('id')
                    },
                    success: function(){
                        self.removeClass('fav').addClass('faved');
                        _updateNotice('成功添加收藏');
                    }
                });
                e.preventDefault();
            });
            
            $('.faved').live('click', function(e){
                var self = $(this);
                $.ajax({
                    url: "ajax/del_fav",
                    type: 'POST',
                    data: {
                        id: self.closest('li').attr('id')
                    },
                    success: function(){
                        self.removeClass('faved').addClass('fav');
                        _updateNotice('成功删除收藏');
                    }
                });
                e.preventDefault();
            });
            
            $('.delete').live('click', function(e){
                e.preventDefault();
                var self = $(this);
                var li = self.closest('li');
                if (!confirm('确定删除？')) 
                    return;
                $.ajax({
                    url: "ajax/del_status",
                    type: 'POST',
                    data: {
                        id: li.attr('id')
                    },
                    success: function(){
                        _updateNotice('成功删除');
                        li.css("background-color", "#FFC").fadeOut(500, function(){
                            li.remove();
                        });
                    }
                });
            });
            
            $('#nextButton').click(function(e){
                var self = $(this);
                if (!self.hasClass('more-enable')) {
                    return;
                }
                self.addClass('more-loading').removeClass('more-enable').html('');
                $.ajax({
                    url: "ajax/home_time_line",
                    cache: false,
                    type: 'POST',
                    data: {
                        max_id: $('#timeline li:last').attr('id')
                    },
                    success: function(html){
                        $('#timeline').find('li:last').addClass('item-solid-border');
                        array = $(html).find('li');
                        for (var i = 1; i < array.length; i++) 
                            $(array[i]).appendTo('#timeline');
                        self.removeClass('more-loading').addClass('more-enable').html('更多');
                    },
                    error: function(){
                        _updateNotice('失败鸟');
                        self.removeClass('more-loading').addClass('more-enable').html('更多');
                    }
                });
                
                e.preventDefault();
            });
	    
	    $('#home-link').click(function(e) {
		$.ajax({
                    url: "ajax/home_time_line",
                    cache: false,
                    type: 'POST',
                    success: function(html){
			timeline.html(html);
                    }
                });
		e.preventDefault();
	    });
            
            $('#updateSubmit').click(function(e){
                $.ajax({
                    url: "ajax/update",
                    type: 'POST',
                    data: {
                        status: $('#status').val(),
                        in_reply_to: $('#in_reply_to').val()
                    },
                    success: function(html){
                        var li = $(html).find('li').addClass('by_me').prependTo("#timeline");
                        $('#status').val('');
                        _updateLatest(li.find('.content').text());
                        _updateTextCounter();
                        _updateNotice('更新成功');
                        updateCounter.html(parseInt(updateCounter.html()) + 1);
                    }
                });
                e.preventDefault();
            });
            
            $('body').click(_reset);
            
            msgBox.click(function(){

                var scrollTop = $(window).scrollTop();
		var tempOffsetTop = $('#footer').offset().top;
				
                timeline.find('.unread:last').addClass('item-solid-border').end()
		    .find('.unread').removeClass('unread').show();
		
                msgBox.hide();
		
		var scrollOffset = $('#footer').offset().top - tempOffsetTop;
		$(window).scrollTop(scrollTop + scrollOffset);
                
                unreadCount = 0;
                _updateTitle();
            });
            
            // Temp
            $('.autoupdate-switch-label').click(_getNewTimeLine);
        }
        
        var _init = function(){
            _attachEvents();
            setInterval(_getNewTimeLine, 1000 * 60);
        }
        return {
            ICON_STATE: _ICON_STATE,
            getNewTimeline: _getNewTimeLine,
            init: _init
        }
    }();
    $(LS.UI.init);
    window['LS'] = LS;
}();
